<template>
  <div class="kawaii-videos">
    <div class="kawaii-filter-section">
      <div class="kawaii-sort-options">
        <div
          v-for="option in sortOptions"
          :key="option.value"
          :class="[
            'kawaii-btn-filter',
            { active: currentSort === option.value },
          ]"
          @click="changeSort(option.value)"
        >
          {{ option.label }}
        </div>
      </div>
    </div>

    <!-- 视频列表 -->
    <div v-if="loading && videos.length === 0" class="kawaii-loading-container">
      <div class="kawaii-loading">
        <div class="kawaii-loading-circle"></div>
        <div class="kawaii-loading-text">加载中...</div>
      </div>
    </div>

    <div v-else-if="videos.length === 0" class="kawaii-empty-result">
      <img
        src="@/assets/icons/empty-box.svg"
        alt="暂无数据"
        class="kawaii-empty-icon"
      />
      <p class="kawaii-empty-text">暂无投稿视频 (￣▽￣)"</p>
      <p class="kawaii-empty-suggestion" v-if="isOwnSpace">
        快去发布你的第一个视频吧 ヽ(✿ﾟ▽ﾟ)ノ
      </p>
    </div>

    <VideoList
      v-else
      :videos="videos"
      :loading="loading"
      :no-more="noMore"
      @loadMore="loadMore"
      :userId="userId"
    />

    <!-- 确认删除对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="30%"
      class="kawaii-dialog"
    >
      <span>
        确定要删除视频 "{{ selectedVideo?.title }}" 吗？此操作不可撤销。
      </span>
      <template #footer>
        <span class="kawaii-dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
import VideoList from '@/views/front/videoList/VideoList.vue'

interface Video {
  id: number | string
  title: string
  thumbnail: string
  duration: number // 视频时长（秒）
  viewCount: number
  danmuCount: number
  likeCount: number
  collectCount: number
  createTime: string
  author: string
  tags: string[]
}

const props = defineProps({
  userId: {
    type: [String, Number],
    required: true,
  },
})

const router = useRouter()
const userStore = useUserStore()

// 是否是用户自己的空间
const isOwnSpace = computed(() => {
  const userInfo = userStore.userInfo
  return props.userId === userInfo?.id
})

// 状态变量
const videos = ref<Video[]>([])
const loading = ref(true)
const noMore = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const deleteDialogVisible = ref(false)
const selectedVideo = ref<Video | null>(null)

// 排序选项
const sortOptions = [
  { label: '最新发布', value: 'latest' },
  { label: '最多播放', value: 'views' },
  { label: '最多收藏', value: 'favorites' },
]

// 当前排序方式
const currentSort = ref('latest')

// 格式化数字
const formatCount = (count: number) => {
  if (!count && count !== 0) return '-'
  if (count === 0) return '-'

  if (count < 10000) {
    return count.toString()
  } else if (count < 100000000) {
    return (count / 10000).toFixed(1) + '万'
  } else {
    return (count / 100000000).toFixed(1) + '亿'
  }
}

// 格式化视频时长
const formatDuration = (seconds: number) => {
  if (!seconds) return '00:00'

  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = Math.floor(seconds % 60)

  return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`
}

// 生成模拟视频数据
const generateMockVideos = (page: number, pageSize: number, sort: string) => {
  const mockVideos: Video[] = []

  const userId = props.userId
  const authorName = `UP主${userId}`

  // 二次元相关标题
  const animeVideoTitles = [
    '【AMV】最燃的动漫打斗场景混剪',
    '【ASMR】给你的夏日带来清凉的声音',
    '【MAD】那些让人落泪的动漫名场面',
    '【剧评】为什么《进击的巨人》能成为现象级作品',
    '【原创】我画了宫崎骏所有角色',
    '【配音】用10种声音演绎动漫名场景',
    '【漫评】最被低估的动漫Top10',
    '【日语】声优教你说最常用的日语短句',
    '【二次元】那些让人惊艳的女主角形象',
    '【解析】动漫中的物理现象是否合理',
    '【盘点】年度最佳动漫音乐',
    '【手绘】从零开始学画漫画人物',
    '【拆解】经典动漫场景分镜头分析',
    '【换装】给动漫角色设计新服装',
    '【考据】动漫中的历史真相与误区',
  ]

  // 动漫相关标签
  const animeTags = [
    '动画',
    '二次元',
    'MAD',
    'AMV',
    '漫画改',
    '原创',
    '日漫',
    '国漫',
    '欧美动画',
    '治愈',
    '热血',
    '声优',
    '催泪',
    '解说',
    '安利',
  ]

  // 根据当前页计算起始索引
  const startIndex = (page - 1) * pageSize

  for (let i = 0; i < pageSize; i++) {
    const id = startIndex + i + 1
    const viewCount = Math.floor(Math.random() * 1000000)

    // 创建时间递减，使得排序更真实
    const date = new Date()
    date.setDate(date.getDate() - id)

    // 随机选择标题、标签和封面
    const titleIndex = Math.floor(Math.random() * animeVideoTitles.length)
    const coverIndex = Math.floor(Math.random() * 15) + 1

    // 随机选择1-3个标签
    const tagCount = Math.floor(Math.random() * 3) + 1
    const videoTags: string[] = []

    for (let j = 0; j < tagCount; j++) {
      const tagIndex = Math.floor(Math.random() * animeTags.length)
      if (!videoTags.includes(animeTags[tagIndex])) {
        videoTags.push(animeTags[tagIndex])
      }
    }

    const title =
      animeVideoTitles[titleIndex] +
      (id % 2 === 0 ? '【第' + ((id % 5) + 1) + '集】' : '')

    mockVideos.push({
      id: id,
      title: title,
      thumbnail: `/src/assets/anime/images/banner${coverIndex}.png`,
      duration: Math.floor(Math.random() * 600) + 60, // 1-11分钟
      viewCount: viewCount,
      danmuCount: Math.floor(viewCount * (Math.random() * 0.2)),
      likeCount: Math.floor(viewCount * (Math.random() * 0.1)),
      collectCount: Math.floor(viewCount * (Math.random() * 0.05)),
      createTime: formatDate(date),
      author: authorName,
      tags: videoTags, // 添加标签
    })
  }

  // 根据排序方式排序
  if (sort === 'views') {
    mockVideos.sort((a, b) => b.viewCount - a.viewCount)
  } else if (sort === 'favorites') {
    mockVideos.sort((a, b) => b.collectCount - a.collectCount)
  } else {
    // 已经按时间排序了，无需额外处理
  }

  return mockVideos
}

// 格式化日期
const formatDate = (date: Date) => {
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  // 小于一天，显示x小时前
  if (diff < 86400000) {
    // 24 * 60 * 60 * 1000
    const hours = Math.floor(diff / 3600000)
    return hours > 0 ? `${hours}小时前` : '刚刚'
  }

  // 小于一个月，显示x天前
  if (diff < 2592000000) {
    // 30 * 24 * 60 * 60 * 1000
    return `${Math.floor(diff / 86400000)}天前`
  }

  // 否则显示具体日期
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 改变排序方式
const changeSort = (sort: string) => {
  if (sort === currentSort.value) return

  currentSort.value = sort
  currentPage.value = 1
  videos.value = []
  noMore.value = false
  fetchVideos()
}

// 获取视频数据
const fetchVideos = async () => {
  if (loading.value && videos.value.length > 0) return
  loading.value = true

  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 800))

    // 模拟获取视频列表
    const newVideos = generateMockVideos(
      currentPage.value,
      pageSize.value,
      currentSort.value,
    )

    // 模拟已经到达最后一页
    if (currentPage.value >= 3) {
      noMore.value = true
    }

    // 添加到视频列表
    videos.value =
      currentPage.value === 1 ? newVideos : [...videos.value, ...newVideos]
  } catch (error) {
    console.error('获取视频列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载更多视频
const loadMore = () => {
  if (loading.value || noMore.value) return

  currentPage.value++
  fetchVideos()
}

// 删除视频
const deleteVideo = (video: Video) => {
  selectedVideo.value = video
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 500))

    if (selectedVideo.value) {
      // 从列表中移除
      videos.value = videos.value.filter(
        (v) => v.id !== selectedVideo.value!.id,
      )
    }

    // 成功提示
    alert('删除成功')
  } catch (error) {
    console.error('删除视频失败:', error)
    alert('删除失败，请重试')
  } finally {
    deleteDialogVisible.value = false
    selectedVideo.value = null
  }
}

// 监听userId变化，重新获取数据
watch(
  () => props.userId,
  () => {
    currentPage.value = 1
    videos.value = []
    noMore.value = false
    fetchVideos()
  },
)

// 初始化
onMounted(() => {
  fetchVideos()
})
</script>

<style scoped lang="scss">
.kawaii-videos {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.kawaii-filter-section {
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 16px;
  padding: 12px 20px;
  box-shadow: 0 4px 10px rgba(255, 182, 193, 0.2);
  border: 2px solid rgba(255, 182, 193, 0.3);
  backdrop-filter: blur(5px);
}

.kawaii-sort-options {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.kawaii-btn-filter {
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  background: rgba(255, 255, 255, 0.8);
  color: #7c5479;
  border: 2px solid transparent;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(255, 182, 193, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(255, 182, 193, 0.3);
    border-color: rgba(255, 182, 193, 0.5);
  }

  &.active {
    background: linear-gradient(to right, #ffcbe3, #ffd6ff);
    border-color: rgba(255, 182, 193, 0.7);
    box-shadow: 0 4px 10px rgba(255, 182, 193, 0.3);
    font-weight: bold;

    &::before {
      content: '✨';
      margin-right: 5px;
      font-size: 12px;
    }
  }
}

.kawaii-loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.kawaii-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.kawaii-loading-circle {
  width: 50px;
  height: 50px;
  border: 4px solid #ffcbe3;
  border-top-color: #fe4ea4;
  border-radius: 50%;
  animation: spin 1s infinite linear;
}

.kawaii-loading-text {
  color: #7c5479;
  font-size: 16px;
  font-weight: bold;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.kawaii-empty-result {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 10px rgba(255, 182, 193, 0.2);
  border: 2px solid rgba(255, 182, 193, 0.3);
  backdrop-filter: blur(5px);
}

.kawaii-empty-icon {
  width: 120px;
  height: 120px;
  margin-bottom: 20px;
  animation: float 3s infinite ease-in-out;
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-10px);
  }
}

.kawaii-empty-text {
  font-size: 18px;
  color: #7c5479;
  font-weight: bold;
  margin-bottom: 10px;
}

.kawaii-empty-suggestion {
  font-size: 14px;
  color: #99809d;
}

.kawaii-dialog {
  :deep(.el-dialog__header) {
    background: linear-gradient(to right, #ffcbe3, #ffd6ff);
    padding: 15px 20px;
    border-radius: 10px 10px 0 0;
  }

  :deep(.el-dialog__title) {
    color: #7c5479;
    font-weight: bold;
  }

  :deep(.el-dialog__body) {
    background-color: #fff;
    padding: 20px;
    color: #7c5479;
  }

  :deep(.el-dialog__footer) {
    background-color: #fff;
    padding: 10px 20px 20px;
    border-radius: 0 0 10px 10px;
  }
}

.kawaii-dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;

  :deep(.el-button) {
    border-radius: 20px;
  }

  :deep(.el-button--default) {
    border-color: #b5a9d4;
    color: #7c5479;

    &:hover {
      border-color: #c9a0dc;
      background-color: rgba(201, 160, 220, 0.1);
    }
  }

  :deep(.el-button--danger) {
    background: linear-gradient(to right, #ff6a88, #ff99ac);
    border: none;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(255, 106, 136, 0.3);
    }
  }
}
</style>
